import {useReducer} from "react";

const initialState = {
    count: 0
}

const reducer = (initialState, action) => {
    let actionMap = new Map();
    actionMap.set('add', function() {
        return {
            count: initialState.count + 1
        }
    })
    actionMap.set('minus', function() {
        return {
            count: initialState.count - 1
        }
    })
    actionMap.set('reset', function() {
        return {
            count: 0
        }
    })
    if (actionMap.get(action.type)) {
        return actionMap.get(action.type)();
    } else {
        return {
            count: 0
        }
    }
}

function Demo () {
    const [countState, dispatch] = useReducer(reducer, initialState);
    return (
        <div className="container border">
            <p className="title">Demo--useReducer--1</p>
            <h1>{countState.count}</h1>
            <button onClick={() => {dispatch({ type: 'add' })}}>Add</button>
            <button onClick={() => {dispatch({ type: 'minus' })}}>Minus</button>
            <button onClick={() => {dispatch({ type: 'reset' })}}>Resset</button>
            <button onClick={() => {dispatch({ type: '' })}}>default</button>
        </div>
    )
}

export default Demo;